<?php

// +----------------------------------------------------------------------

// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]

// +----------------------------------------------------------------------

// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.

// +----------------------------------------------------------------------

// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )

// +----------------------------------------------------------------------

// | Author: 小夏 < 449134904@qq.com>

// +----------------------------------------------------------------------

namespace app\admin\controller;

use app\admin\model\AccessModel;
use app\admin\model\AttendanceModel;
use cmf\controller\AdminBaseController; //权限查询

use PHPExcel_Cell;
use PHPExcel_Style_Alignment;
use think\Db;
use think\Request;
use tree\Tree;

/**

 * Class UserController

 * @package app\admin\controller

 * @adminMenuRoot(

 *     'name'   => '管理组',

 *     'action' => 'default',

 *     'parent' => 'user/AdminIndex/default',

 *     'display'=> true,

 *     'order'  => 10000,

 *     'icon'   => '',

 *     'remark' => '管理组'

 * )

 */

class UserController extends AdminBaseController
{

    public $departmentids = array();

    /**

     * 用户状态

     */

    private $statusStr = ['禁用', '正常'];

    /**

     * 管理员列表

     * @adminMenu(

     *     'name'   => '管理员',

     *     'parent' => 'default',

     *     'display'=> true,

     *     'hasView'=> true,

     *     'order'  => 10000,

     *     'icon'   => '',

     *     'remark' => '管理员管理',

     *     'param'  => ''

     * )

     */

    public function index()
    {

        //获取管理员列表信息

        $userList = Db::name('user')->paginate(20);

        $company = Db::name('company')->where('id', 1)->find();

        foreach ($userList as $key => $value) {

            //获取用户部门//获取用户角色

            $userAttach = Db::name('user_attach')->where('user_id', $value['id'])->find();

            $value['department'] = Db::name('department')->where('id', $userAttach['department_id'])->value('name');

            $value['role'] = Db::name('role')->where('id', $userAttach['role_id'])->value('name');

            $userList[$key] = $value;

        }

        $this->assign('company', $company);

        $this->assign('userList', $userList);

        $this->assign('statusStr', $this->statusStr);

        return $this->fetch();

    }

    //部门下溯各个子部门

    public function getDepartment($departmentid)
    {

        $departments = Db::name('department')->where(['parent_id' => $departmentid])->column('id');

        if (count($departments) != 0) {

            array_push($this->departmentids, $departments);

        }

        for ($i = 0; $i < count($departments); $i++) {

            $departmentid = $departments[$i];

            $this->getDepartment($departmentid);

        }

    }

    //角色列表

    public function roleList()
    {

        $result = Db::name('role')->column('');

        $tree = new Tree();

        $tree->icon = ['│ ', '├─ ', '└─ '];

        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';

        foreach ($result as $m) {

            $newMenus[$m['id']] = $m;

        }

        foreach ($result as $n => $t) {

            $result[$n]['level'] = $this->_getLevel($t['id'], $newMenus);

            $result[$n]['style'] = empty($t['parent_id']) ? '' : 'display:none;';

            $result[$n]['parentIdNode'] = ($t['parent_id']) ? ' class="child-of-node-' . $t['parent_id'] . '"' : '';

        }

        $str = "<option value = \$id>

                <tr id='node-\$id'\$parentIdNode  style='\$style'>

                   <td style='padding-left:30px;'>\$spacer\$name</td>

                </tr>

                </option>";

        $tree->init($result);

        $role = $tree->getTree(0, $str);

        $this->assign('rolelist', $role);

    }

    //部门列表

    public function department()
    {

        $result = Db::name('department')->column('');

        $tree = new Tree();

        $tree->icon = ['│ ', '├─ ', '└─ '];

        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';

        foreach ($result as $m) {

            $newMenus[$m['id']] = $m;

        }

        foreach ($result as $n => $t) {

            $result[$n]['level'] = $this->_getLevel($t['id'], $newMenus);

            $result[$n]['style'] = empty($t['parent_id']) ? '' : 'display:none;';

            $result[$n]['parentIdNode'] = ($t['parent_id']) ? ' class="child-of-node-' . $t['parent_id'] . '"' : '';

        }

        $str2 = "<option value = \$id>

                <tr id='node-\$id'\$parentIdNode  style='\$style'>

                   <td style='padding-left:30px;'>\$spacer\$name</td>

                </tr>

                </option>";

        $tree->init($result);

        $department = $tree->getTree(0, $str2);

        $this->assign('department', $department);

    }

    /**

     * 获取菜单深度

     * @param $id

     * @param array $array

     * @param int $i

     * @return int

     */

    protected function _getLevel($id, $array = [], $i = 0)
    {

        if ($array[$id]['parent_id'] == 0 || empty($array[$array[$id]['parent_id']]) || $array[$id]['parent_id'] == $id) {

            return $i;

        } else {

            $i++;

            return $this->_getLevel($array[$id]['parent_id'], $array, $i);

        }

    }

    /**

     * 管理员添加

     * @adminMenu(

     *     'name'   => '管理员添加',

     *     'parent' => 'index',

     *     'display'=> false,

     *     'hasView'=> true,

     *     'order'  => 10000,

     *     'icon'   => '',

     *     'remark' => '管理员添加',

     *     'param'  => ''

     * )

     */

    public function add()
    {

        $roles = Db::name('role')->where(['status' => 1])->order("id DESC")->select();

        $id = cmf_get_current_admin_id();

        $info = Db::name('user_attach')->where(['user_id' => $id])->select();

        //读取所在公司角色列表 并分层级

        //读取当前登入账号所在的公司

        $accessModel = new AccessModel();

        $company = $accessModel->get_company_info();

        //读取所在公司角色列表 并分层级

        $accessModel = new AccessModel();

        //获取当前用户所在公司角色列表信息

        $roles = $accessModel->get_company_role_list();

        $result = $roles;

        $tree = new Tree();

        //角色

        $tree->icon = ['│ ', '├─ ', '└─ '];

        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';

        foreach ($result as $m) {

            $newMenus[$m['id']] = $m;

        }

        foreach ($result as $n => $t) {

            $result[$n]['level'] = $this->_getLevel($t['id'], $newMenus);

            $result[$n]['style'] = empty($t['parent_id']) ? '' : 'display:none;';

            $result[$n]['parentIdNode'] = ($t['parent_id']) ? ' class="child-of-node-' . $t['parent_id'] . '"' : '';

        }

        $str2 = "<option value = \$id data-dep=\$department_id>\$spacer\$name</option>";

        $tree->init($result);

        $role = $tree->getTree(0, $str2);

// dump($company['id']);

        $this->assign('roleList', $role);

        // $this->assign('company',$company['id']);

        $this->assign('company', $company);

        $this->assign("roles", $roles);

        $this->assign("userid", $id);

        // $this->roleList();

        return $this->fetch();

    }

    public function user_index(){
        return $this->fetch();
    }

    public function leader_index(){
        return $this->fetch();
    }
    public function talent_management(){
        return $this->fetch();
    }

    public function rank(){
        return $this->fetch();
    }
    public function department_charge_audit(){
        return $this->fetch();
    }

    /**
     * 优秀处导出
     */
    public function exportExcellenceExcel()
    {
        $param = $this->request->param();
        $month = date('m', time());
        if(!empty($param['month'])){
            $month = $param['month'];
        }
        $year = date('Y', time());
        $uid = $param['uid'];
        if(!empty($uid)){
            $user = Db::name('user')->where('id',$uid)->find();
            $tableData = Db::name('department_sj')->where('uid',$uid)->where('type',1)->where('month',$month)->where('year',$year)->select();//优秀处
            $this->exportExcelForExcellence($tableData,$user['user_login']);
        }
    }
    public function exportExcelForExcellence($list,$username){
        //2.加载PHPExcle类库
        vendor('PHPExcel.PHPExcel');
        //3.实例化PHPExcel类
        $objPHPExcel = new \PHPExcel();
        //4.激活当前的sheet表
        $objPHPExcel->setActiveSheetIndex(0);
        //5.设置表格头（即excel表格的第一行）
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '序号')
            ->setCellValue('B1', '优秀处')
            ->setCellValue('C1', '考核项目')
            ->setCellValue('D1', '考核依据及办法')
            ->setCellValue('E1', '个人自评分')
            ->setCellValue('F1', '处室负责人评分')
            ->setCellValue('G1', '审定分')
            ->setCellValue('H1', '得分概述');
        //设置A列水平居中
//        $objPHPExcel->setActiveSheetIndex(0)->getStyle('A1')->getAlignment()
//            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        //设置单元格宽度
//        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('B')->setWidth(20);
        foreach ($list as $i=>$item){
            $objPHPExcel->getActiveSheet()->setCellValue('A'.($i+2),$item['serial']);
            $objPHPExcel->getActiveSheet()->setCellValue('B'.($i+2),$item['department']);
            $objPHPExcel->getActiveSheet()->setCellValue('C'.($i+2),$item['name']);
            $objPHPExcel->getActiveSheet()->setCellValue('D'.($i+2),$item['amount1']);
            $objPHPExcel->getActiveSheet()->setCellValue('E'.($i+2),$item['amount2']);
            $objPHPExcel->getActiveSheet()->setCellValue('F'.($i+2),$item['amount6']);
            $objPHPExcel->getActiveSheet()->setCellValue('G'.($i+2),$item['amount3']);
            $objPHPExcel->getActiveSheet()->setCellValue('H'.($i+2),$item['content']);
        }
        $objPHPExcel->getActiveSheet()->mergeCells('A3:A7');//合并单元格
        $objPHPExcel->getActiveSheet()->mergeCells('B3:B7');//合并单元格
        $objPHPExcel->getActiveSheet()->mergeCells('C3:C7');//合并单元格
        $objPHPExcel->getActiveSheet()->mergeCells('A8:A10');//合并单元格
        $objPHPExcel->getActiveSheet()->mergeCells('B8:B10');//合并单元格
        $objPHPExcel->getActiveSheet()->mergeCells('C8:C10');//合并单元格
        $objPHPExcel->getActiveSheet()->mergeCells('A11:A13');//合并单元格
        $objPHPExcel->getActiveSheet()->mergeCells('B11:B13');//合并单元格
        $objPHPExcel->getActiveSheet()->mergeCells('A14:A16');//合并单元格
        $objPHPExcel->getActiveSheet()->mergeCells('B14:B16');//合并单元格
        $objPHPExcel->getActiveSheet()->mergeCells('C14:C16');//合并单元格
        $objPHPExcel->getActiveSheet()->mergeCells('A18:A20');//合并单元格
        $objPHPExcel->getActiveSheet()->mergeCells('B18:B20');//合并单元格
        $objPHPExcel->getActiveSheet()->mergeCells('C18:C20');//合并单元格
        $objPHPExcel->getActiveSheet()->mergeCells('A21:A24');//合并单元格
        $objPHPExcel->getActiveSheet()->mergeCells('B21:B24');//合并单元格
        $objPHPExcel->getActiveSheet()->mergeCells('C21:C24');//合并单元格
        $objPHPExcel->getActiveSheet()->mergeCells('A30:A31');//合并单元格
        $objPHPExcel->getActiveSheet()->mergeCells('B30:B31');//合并单元格
        $objPHPExcel->getActiveSheet()->mergeCells('C30:C31');//合并单元格
        $objPHPExcel->getActiveSheet()->mergeCells('A32:A36');//合并单元格
        $objPHPExcel->getActiveSheet()->mergeCells('B32:B36');//合并单元格
        $objPHPExcel->getActiveSheet()->mergeCells('C32:C36');//合并单元格

        $objPHPExcel->getActiveSheet()->getStyle('A3:A7')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('B3:B7')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('C3:C7')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('A8:A10')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('B8:B10')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('C8:C10')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('A11:A13')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('B11:B13')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('A14:A16')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('B14:B16')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('C14:C16')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('A18:A20')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('B18:B20')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('C18:C20')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('A21:A24')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('B21:B24')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('C21:C24')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('A30:A31')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('B30:B31')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('C30:C31')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('A32:A36')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('B32:B36')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('C32:C36')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);

        //7.设置保存的Excel表格名称
        $filename = $username.'个人评分表'.date('ymd',time()).'.xls';
        //8.设置当前激活的sheet表格名称；
        $objPHPExcel->getActiveSheet()->setTitle('人员名单');
        //9.设置浏览器窗口下载表格
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:inline;filename="'.$filename.'"');
        //生成excel文件
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        //下载文件在浏览器窗口
        $objWriter->save('php://output');
        exit;
    }

    /**
     * 县市区导出
     */
    public function exportPersonalExcel()
    {
        $param = $this->request->param();
        $month = date('m', time());
        if(!empty($param['month'])){
            $month = $param['month'];
        }
        $year = date('Y', time());
        $departmentId = $param['departmentId'];
        $tableData = Db::name('department_sj')->where('department_id',$departmentId)->where('month',$month)->where('year',$year)->where('type>1')->select();//县市区
        $this->exportExcelForPersonal($tableData);
    }

    public function exportExcelForPersonal($list){
        //2.加载PHPExcle类库
        vendor('PHPExcel.PHPExcel');
        //3.实例化PHPExcel类
        $objPHPExcel = new \PHPExcel();
        //4.激活当前的sheet表
        $objPHPExcel->setActiveSheetIndex(0);
        //5.设置表格头（即excel表格的第一行）
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '序号')
            ->setCellValue('B1', '考核项目')
            ->setCellValue('C1', '考核依据及办法')
            ->setCellValue('D1', '基本分')
            ->setCellValue('E1', '单位自评分')
            ->setCellValue('F1', '审定分')
            ->setCellValue('G1', '得分概述');
        //设置A列水平居中
//        $objPHPExcel->setActiveSheetIndex(0)->getStyle('A1')->getAlignment()
//            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        //设置单元格宽度
//        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('B')->setWidth(20);
        $club_name = '';
        foreach ($list as $i=>$item){
            $objPHPExcel->getActiveSheet()->setCellValue('A'.($i+2),$item['serial']);
            $objPHPExcel->getActiveSheet()->setCellValue('B'.($i+2),$item['name']);
            $objPHPExcel->getActiveSheet()->setCellValue('C'.($i+2),$item['amount1']);
            $objPHPExcel->getActiveSheet()->setCellValue('D'.($i+2),$item['amount4']);
            $objPHPExcel->getActiveSheet()->setCellValue('E'.($i+2),$item['amount2']);
            $objPHPExcel->getActiveSheet()->setCellValue('F'.($i+2),$item['amount3']);
            $objPHPExcel->getActiveSheet()->setCellValue('G'.($i+2),$item['content']);
            $club_name = $item['department'];
        }
        $objPHPExcel->getActiveSheet()->mergeCells('A4:A5');//合并单元格
        $objPHPExcel->getActiveSheet()->mergeCells('B4:B5');//合并单元格
        $objPHPExcel->getActiveSheet()->mergeCells('A6:A10');//合并单元格
        $objPHPExcel->getActiveSheet()->mergeCells('B6:B10');//合并单元格
        $objPHPExcel->getActiveSheet()->mergeCells('A17:A19');//合并单元格
        $objPHPExcel->getActiveSheet()->mergeCells('B17:B19');//合并单元格
        $objPHPExcel->getActiveSheet()->mergeCells('A20:A21');//合并单元格
        $objPHPExcel->getActiveSheet()->mergeCells('B20:B21');//合并单元格
        $objPHPExcel->getActiveSheet()->mergeCells('A22:A23');//合并单元格
        $objPHPExcel->getActiveSheet()->mergeCells('B22:B23');//合并单元格
        $objPHPExcel->getActiveSheet()->mergeCells('A26:A28');//合并单元格
        $objPHPExcel->getActiveSheet()->mergeCells('B26:B28');//合并单元格
        $objPHPExcel->getActiveSheet()->mergeCells('A29:A31');//合并单元格
        $objPHPExcel->getActiveSheet()->mergeCells('B29:B31');//合并单元格
        $objPHPExcel->getActiveSheet()->mergeCells('A33:A34');//合并单元格
        $objPHPExcel->getActiveSheet()->mergeCells('B33:B34');//合并单元格


        $objPHPExcel->getActiveSheet()->getStyle('A4:A5')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('B4:B5')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('A6:A10')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('B6:B10')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('A17:A19')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('B17:B19')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('A20:A21')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('B20:B21')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('A22:A23')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('B22:B23')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('A26:A28')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('B26:B28')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('A29:A31')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('B29:B31')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('A33:A34')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('B33:B34')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        //7.设置保存的Excel表格名称
        $filename = $club_name.'评分表'.date('ymd',time()).'.xls';
        //8.设置当前激活的sheet表格名称；
        $objPHPExcel->getActiveSheet()->setTitle('人员名单');
        //9.设置浏览器窗口下载表格
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:inline;filename="'.$filename.'"');
        //生成excel文件
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        //下载文件在浏览器窗口
        $objWriter->save('php://output');
        exit;
    }


    /**
     * 导出该部门下的所有成员的各个总分
     */
    public function exportDepartmentList(){
        $month = date('m',time());
        $year = date('Y',time());
        $param = $this->request->param();
        if(empty($param['department_id'])){
            return zy_json_echo(false, "未获取到部门id", '', 300);
        }
        $department_id = $param['department_id'];//部门id
        $where = 'status=1 and type=1 and department_id='.$department_id.' and year='.$year;
        if($param['type'] == 1){
            $where.=' and month='.$month;
        }

        $departmentDetail = Db::name('department')->where('id',$department_id)->find();
        $club_name = $departmentDetail['name'];

        $list = Db::name('rank_history')->where($where)->select()->each(function ($item) use ($param, $department_id, $year, $month) {
            $user = Db::name('user')->where('id',$item['uid'])->find();
            $item['user_name'] = $user['user_login'];
            $content = '';

            $item_where = 'type=1 and year='.$year.' and department_id='.$department_id.' and uid='.$item['uid'];
            if($param['type'] == 1){
                $item_where.=' and month='.$month;
            }
            $departmentList = Db::name('department_sj')->where($item_where)->select();
            foreach ($departmentList as $d_item){
                $content .= $d_item['content'];
            }
            $item['content'] = $content;
            return $item;
        });
        $this->exportExcel($list,$club_name);
    }

    public function exportExcel($list,$club_name){
        //2.加载PHPExcle类库
        vendor('PHPExcel.PHPExcel');
        //3.实例化PHPExcel类
        $objPHPExcel = new \PHPExcel();
        //4.激活当前的sheet表
        $objPHPExcel->setActiveSheetIndex(0);
        //5.设置表格头（即excel表格的第一行）
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '姓名')
            ->setCellValue('B1', '总分')
            ->setCellValue('C1', '得分概述');
        //设置A列水平居中
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('A1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        //设置单元格宽度
        //6.循环刚取出来的数组，将数据逐一添加到excel表格。
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('B')->setWidth(20);

        foreach ($list as $i=>$item){
            $objPHPExcel->getActiveSheet()->setCellValue('A'.($i+2),$item['user_name']);
            $objPHPExcel->getActiveSheet()->setCellValue('B'.($i+2),$item['leader_grade']);
            $objPHPExcel->getActiveSheet()->setCellValue('C'.($i+2),$item['content']);
        }
        //7.设置保存的Excel表格名称
        $filename = $club_name.'人员名单'.date('ymd',time()).'.xls';
        //8.设置当前激活的sheet表格名称；
        $objPHPExcel->getActiveSheet()->setTitle('人员名单');
        //9.设置浏览器窗口下载表格
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:inline;filename="'.$filename.'"');
        //生成excel文件
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        //下载文件在浏览器窗口
        $objWriter->save('php://output');
        exit;
    }



    /**
     * 获取该部门下的所有成员的各个总分
     */
    public function getDepartmentList(){
        $month = date('m',time());
        $year = date('Y',time());
        $param = $this->request->param();
        if(empty($param['department_id'])){
            return zy_json_echo(false, "未获取到部门id", '', 300);
        }
        $department_id = $param['department_id'];//部门id
        $where = 'status=1 and type=1 and department_id='.$department_id.' and year='.$year;
        if($param['type'] == 1){
            $where.=' and month='.$month;
        }

        $list = Db::name('rank_history')->where($where)->select()->each(function ($item) use ($param, $department_id, $year, $month) {
            $user = Db::name('user')->where('id',$item['uid'])->find();
            $item['user_name'] = $user['user_login'];
            $content = '';

            $item_where = 'type=1 and year='.$year.' and department_id='.$department_id.' and uid='.$item['uid'];
            if($param['type'] == 1){
                $item_where.=' and month='.$month;
            }
            $departmentList = Db::name('department_sj')->where($item_where)->select();
            foreach ($departmentList as $d_item){
                $content .= $d_item['content'];
            }
            $item['content'] = $content;
            return $item;
        });
        return zy_json_echo(true, "查询成功", $list, 200);
    }

    /**
     * 获取当余月评分
     */
    public function getCurrentGrade(){
        $month = date('m',time());
        $year = date('Y',time());
        $uid = cmf_get_current_admin_id();
        //历史累计分数
        $history_score = 0;
        //历史评分
        $history_list = Db::name('rank_history')->where('month <'.$month)->where('year',$year)->where('uid',$uid)->select()->each(function ($item) use ($history_score) {
            $item['add_time'] = date('Y-m-d H:i:s',$item['add_time']);
            if(!empty($item['my_grade_time'])){
                $item['my_grade_time'] = date('Y-m-d H:i:s',$item['my_grade_time']);
            }
            if(!empty($item['leader_grade_time'])){
                $item['leader_grade_time'] = date('Y-m-d H:i:s',$item['leader_grade_time']);
            }
            $curr_score = 0;
            if(!empty($item['leader_grade'])){
                $curr_score = $item['leader_grade'];
            }
            $item['history_score'] = $history_score+$curr_score;
            $history_score += $curr_score;
            $item['status_str'] = '未填写';
            if($item['status'] == 1){
                $item['status_str'] = '已填写';
            }
            return $item;
        });
        //当月评分
        $list = Db::name('rank_history')->where('month',$month)->where('year',$year)->where('uid',$uid)->select()->each(function ($item) use ($history_score) {
            $item['add_time'] = date('Y-m-d H:i:s',$item['add_time']);
            if(!empty($item['my_grade_time'])){
                $item['my_grade_time'] = date('Y-m-d H:i:s',$item['my_grade_time']);
            }
            if(!empty($item['leader_grade_time'])){
                $item['leader_grade_time'] = date('Y-m-d H:i:s',$item['leader_grade_time']);
            }
            $curr_score = 0;
            if(!empty($item['leader_grade'])){
                $curr_score = $item['leader_grade'];
            }
            $item['history_score'] = $history_score+$curr_score;
            $item['status_str'] = '未填写';
            if($item['status'] == 1){
                $item['status_str'] = '已填写';
            }
            return $item;
        });
        //获取用户信息
        $user = Db::name('user')->where('id',$uid)->find();
        if($user['sex']==0){
            $user['sex'] = '保密';
        }elseif($user['sex']==1){
            $user['sex'] = '男';
        }elseif($user['sex']==2){
            $user['sex'] = '女';
        }
        $attachDetail = Db::name('user_attach')->where('user_id', $uid)->find();
        $userDetail = Db::name('department')->where('id', $attachDetail['department_id'])->find();
        $user['department'] = $userDetail['name'];
        $user['avatar'] = ZY_APP_PATH.'upload/'.$user['avatar'];


        $needle = 0;
        $tmparray = explode($attachDetail['role_id'],'26,27,28,29,31,32');//判断是否包含a这个字符

        if(count($tmparray)>1){
            $needle = 1;
        }

        $res = [
            'list'=>$list,
            'history_list'=>$history_list,
            'user'=>$user,
            'departmentId'=>$attachDetail['department_id'],
            'roleId'=>$needle
        ];
        return zy_json_echo(true, "查询成功", $res, 200);
    }

    /**
     * 每个月自动生成评分表
     */
    public function autoCreateRank(){
        $month = date('m',time());
        $year = date('Y',time());

        //省地区
        //查询九个市区的用户
        $attach_where = ' department_id in (13,14,15,16,17,18,19,20,21) ';
        $user_list = Db::name('user_attach')->where($attach_where)->select();
        foreach ($user_list as $item){
            //查询当月是否已经创建了记录
            $counts = Db::name('rank_history')->where('type',2)->where('month',$month)->where('year',$year)->where('uid',$item['user_id'])->count();
            if($counts == 0){
                $userDetail = Db::name('department')->where('id', $item['department_id'])->find();
                $rank_data['title'] = $year.'年'.$month.'月'.$userDetail['name'].'评比';
                $rank_data['month'] = $month;
                $rank_data['year'] = $year;
                $rank_data['add_time'] = time();
                $rank_data['type'] = 2;
                $rank_data['uid'] = $item['user_id'];
                $rank_data['department_id'] =$item['department_id'];
                Db::name('rank_history')->insert($rank_data);
            }
        }
        //优秀处
        //查询主任和其他的用户
        $attach_normal_where = ' department_id not in (13,14,15,16,17,18,19,20,21) ';
        $user_normal_list = Db::name('user_attach')->where($attach_normal_where)->select();
        foreach ($user_normal_list as $item){
            //查询当月是否已经创建了记录
            $counts = Db::name('rank_history')->where('type',1)->where('month',$month)->where('year',$year)->where('uid',$item['user_id'])->count();
            if($counts == 0){
                $userDetail = Db::name('department')->where('id', $item['department_id'])->find();
                $rank_data['title'] = $year.'年'.$month.'月'.$userDetail['name'].'评比';
                $rank_data['month'] = $month;
                $rank_data['year'] = $year;
                $rank_data['add_time'] = time();
                $rank_data['type'] = 1;
                $rank_data['uid'] = $item['user_id'];
                $rank_data['department_id'] =$item['department_id'];
                Db::name('rank_history')->insert($rank_data);
            }
        }
    }

    /**
     * 部门审计 -------------- 开始
     */
    public function department_audit(){
        return $this->fetch();
    }
    public function department_admin_audit(){
        return $this->fetch();
    }

    /**
     * 根据地区获取部门详情和部门总分
     */
    public function getDepartmentDetailByIdForCharge(){
        $res = $this->request->param();
        $uid = $res['uid'];
        //获取已添加的详情
        $month = date('m',time());
        $year = date('Y',time());
        $tableData = Db::name('department_sj')->where('uid',$uid)->where('type',1)->where('month',$month)->where('year',$year)->select()->each(function ($item){
            if($item['status'] == 0){
                $item['amount6'] = $item['amount2'];
            }
            return $item;
        });

        $res=[
            'tableData'=>$tableData,
        ];
        return zy_json_echo(true, "查询成功", $res, 200);
    }


    /**
     * 根据地区获取部门详情和部门总分
     */
    public function getDepartmentDetailById(){
        $res = $this->request->param();
        $uid = $res['uid'];
        //获取已添加的详情
        $month = date('m',time());
        $year = date('Y',time());
        $tableData = Db::name('department_sj')->where('uid',$uid)->where('type',1)->where('month',$month)->where('year',$year)->select()->each(function ($item){
            if($item['status'] == 0){
                $item['amount3'] = $item['amount6'];
            }
            return $item;
        });

        $res=[
            'tableData'=>$tableData,
        ];
        return zy_json_echo(true, "查询成功", $res, 200);
    }
    /**
     * 获取部门详情和部门总分
     */
    public function getDepartmentDetail(){
        $param = $this->request->param();
        $uid = cmf_get_current_admin_id();
        $attachDetail = Db::name('user_attach')->where('user_id', $uid)->find();
        if(empty($attachDetail)){
            return zy_json_echo(false, "获取数据失败,请稍后再试", '', 300);
        }
        $userDetail = Db::name('department')->where('id', $attachDetail['department_id'])->find();
        //获取已添加的详情
        $uid = cmf_get_current_admin_id();
        $month = date('m',time());
        if(!empty($param['month'])){
            $month = $param['month'];
        }
        $year = date('Y',time());
        $tableData = Db::name('department_sj')->where('uid',$uid)->where('month',$month)->where('year',$year)->select();

        $rankDetail = Db::name('rank_history')->where('type',1)->where('month',$month)->where('year',$year)->where('uid',$uid)->find();
        $files_arr = explode(",",$rankDetail['files']);
        $files_name_arr = explode(",",$rankDetail['files_name']);
        $fileList = array();
        foreach ($files_arr as $i=>$item){
           $rs=[
               'name'=>$files_name_arr[$i],
               'url'=>$files_arr[$i],
           ];
           array_push($fileList,$rs);
        }

        $res=[
            'department_name'=>$userDetail['name'],
            'tableData'=>$tableData,
            'fileList'=>$fileList,
            'files'=>$rankDetail['files'],
            'files_name'=>$rankDetail['files_name'],
        ];
        return zy_json_echo(true, "查询成功", $res, 200);
    }




    /**
     * 根据地区获取部门详情和部门总分
     */
    public function getAreaDetailById(){
        $res = $this->request->param();
        $departmentId = $res['departmentId'];
        //获取已添加的详情
        $month = date('m',time());
        $year = date('Y',time());
        $tableData = Db::name('department_sj')->where('department_id',$departmentId)->where('month',$month)->where('year',$year)->where('type',2)->select()->each(function ($item){
            $month = date('m',time());
            $year = date('Y',time());
            if($item['status'] == 0){
                //领导未打分,需要自己计算  1.判断是否需要比例
                $proportion = $item['proportion'];
                if($proportion == 0){
                    $item['amount3'] = $item['amount2'];
                }else{
                    //获取这个月这个项目的最高分
                    $list = Db::name('department_sj')->where('month',$month)->where('year',$year)->where('mark',$item['mark'])->where('type',$item['type'])->order('amount2','desc')->limit(1)->select();
                    $detail = $list[0];
                    if($item['amount2']>0){
                        //没有最高分 自己就是最高分
                        $max_amount2 = $item['amount2'];
                        if(!empty($detail['amount2'])){
                            $max_amount2 = $detail['amount2'];//最高分
                        }
                        $base_grade = $item['amount4'];//基本分
                        $amount2 = $item['amount2'];//个人分
                        //1.判断第 11-1 的项目
                        if($item['mark']=='11-1' || $item['mark']=='11-2'){
                            $base_grade = 4;
                        }
                        if($item['mark']=='11-3'){
                            $base_grade = 5;
                        }
                        $result = $base_grade*($amount2/$max_amount2);
                        if($item['mark']=='11-1' || $item['mark']=='11-2'){
                            $result = $result*(4/13);
                        }
                        if($item['mark']=='11-3'){
                            $result = $result*(5/13);
                        }
                        $item['amount3'] = round($result,2);
                    }
                }
            }
            return $item;
        });
        $tableData_add = Db::name('department_sj')->where('department_id',$departmentId)->where('month',$month)->where('year',$year)->where('type',3)->select()->each(function ($item){
            $month = date('m',time());
            $year = date('Y',time());
            if($item['status'] == 0){
                //领导未打分,需要自己计算  1.判断是否需要比例
                $proportion = $item['proportion'];
                if($proportion == 0){
                    $item['amount3'] = $item['amount2'];
                }else{
                    //获取这个月这个项目的最高分
                    $list = Db::name('department_sj')->where('month',$month)->where('year',$year)->where('mark',$item['mark'])->where('type',$item['type'])->order('amount2','desc')->limit(1)->select();
                    $detail = $list[0];
                    if($item['amount2']>0){
                        //没有最高分 自己就是最高分
                        $max_amount2 = $item['amount2'];
                        if(!empty($detail['amount2'])){
                            $max_amount2 = $detail['amount2'];//最高分
                        }
                        $base_grade = $item['amount4'];//基本分
                        $amount2 = $item['amount2'];//个人分
                        $item['amount3'] = round(($base_grade*($amount2/$max_amount2)),2);
                    }
                }
            }
            return $item;
        });

        $res=[
            'tableData'=>$tableData,
            'tableData_add'=>$tableData_add,
        ];
        return zy_json_echo(true, "查询成功", $res, 200);
    }
    /**
     * 获取县市区详情和县市区总分
     */
    public function getAreaDetail(){
        $param = $this->request->param();
        $uid = cmf_get_current_admin_id();
        $attachDetail = Db::name('user_attach')->where('user_id', $uid)->find();
        if(empty($attachDetail)){
            return zy_json_echo(false, "获取数据失败,请稍后再试", '', 300);
        }
        $userDetail = Db::name('department')->where('id', $attachDetail['department_id'])->find();
        //获取已添加的详情
        $uid = cmf_get_current_admin_id();
        $month = date('m',time());
        if(!empty($param['month'])){
            $month = $param['month'];
        }
        $year = date('Y',time());
        $tableData = Db::name('department_sj')->where('uid',$uid)->where('month',$month)->where('type',2)->select();
        $tableData_add = Db::name('department_sj')->where('uid',$uid)->where('month',$month)->where('type',3)->select();

        $rankDetail = Db::name('rank_history')->where('type',2)->where('month',$month)->where('year',$year)->where('uid',$uid)->find();
        $files_arr = explode(",",$rankDetail['files']);
        $files_name_arr = explode(",",$rankDetail['files_name']);
        $fileList = array();
        foreach ($files_arr as $i=>$item){
            $rs=[
                'name'=>$files_name_arr[$i],
                'url'=>$files_arr[$i],
            ];
            array_push($fileList,$rs);
        }

        $res=[
            'department_name'=>$userDetail['name'],
            'tableData'=>$tableData,
            'tableData_add'=>$tableData_add,
            'fileList'=>$fileList,
            'files'=>$rankDetail['files'],
            'files_name'=>$rankDetail['files_name'],
        ];
        return zy_json_echo(true, "查询成功", $res, 200);
    }

    /**
     * 添加优秀处分数
     */
    public function addOfficeGrade(){
        $res = $this->request->param();
        $uid = cmf_get_current_admin_id();
        $attachDetail = Db::name('user_attach')->where('user_id', $uid)->find();

        $needle = false;
        $tmparray = explode($attachDetail['role_id'],'26,27,28,29,31,32');//判断是否包含a这个字符
        if(count($tmparray)>1){
            $needle = true;
        }

        $month = date('m',time());
        $year = date('Y',time());
        $list = $res['tableData'];
        foreach ($list as $item){
            if($needle){
                $item['amount6'] =  $item['amount2'];
            }
            $find = Db::name('department_sj')->where('id',$item['d_id'])->find();
            if(empty($find)){
                $item['add_time'] = time();
                $item['month'] =$month;
                $item['year'] = $year;
                $item['uid'] = $uid;
                $item['department_id'] = $attachDetail['department_id'];
                Db::name('department_sj')->insert($item);
            }else{
                $data['amount2'] = $item['amount2'];
                $data['content'] = $item['content'];
                Db::name('department_sj')->where('id',$item['d_id'])->update($data);
            }
        }
        $files_name = $res['files_name'];
        $files = $res['files'];
        $total_grade = $res['total_grade'];
        $find = Db::name('rank_history')->where('type',1)->where('month',$month)->where('year',$year)->where('uid',$uid)->find();
        if(!empty($find)){
            $up_data['status'] = 1;
            $up_data['files'] = $files;
            $up_data['files_name'] = $files_name;
            $up_data['my_grade'] = $total_grade;
            $up_data['my_grade_time'] = time();
            Db::name('rank_history')->where('id',$find['id'])->update($up_data);
        }
        return zy_json_echo(true, "保存成功", '', 200);
    }

    /**
     * 添加县市区分数
     */
    public function addDepartmentGrade(){
        $res = $this->request->param();
        $uid = cmf_get_current_admin_id();
        $attachDetail = Db::name('user_attach')->where('user_id', $uid)->find();
        $month = date('m',time());
        $year = date('Y',time());
        $list = $res['tableData'];
        foreach ($list as $item){
            $find = Db::name('department_sj')->where('id',$item['d_id'])->find();
            if(empty($find)){
                $item['add_time'] = time();
                $item['month'] =$month;
                $item['year'] = $year;
                $item['uid'] = $uid;
                if($uid == 1){
                    $data['amount3'] = $item['amount2'];
                    $data['status'] = 1;
                }
                $item['department_id'] = $attachDetail['department_id'];
                Db::name('department_sj')->insert($item);
            }else{
                if($uid == 1){
                    $data['amount3'] = $item['amount2'];
                    $data['status'] = 1;
                }
                $data['amount2'] = $item['amount2'];
                $data['content'] = $item['content'];
                Db::name('department_sj')->where('id',$item['d_id'])->update($data);
            }
        }
        $files_name = $res['files_name'];
        $files = $res['files'];
        $total_grade = $res['total_grade'];
        $find = Db::name('rank_history')->where('type',2)->where('month',$month)->where('year',$year)->where('uid',$uid)->find();
        if(!empty($find)){
            $up_data['status'] = 1;
            $up_data['files'] = $files;
            $up_data['files_name'] = $files_name;
            $up_data['my_grade'] = $total_grade;
            $up_data['my_grade_time'] = time();
            Db::name('rank_history')->where('id',$find['id'])->update($up_data);
        }
        return zy_json_echo(true, "保存成功", '', 200);
    }

    /**
     * 负责人优秀处打分
     */
    public function addDepartmentGradeByChange(){
        $res = $this->request->param();
        $list = $res['tableData'];
        foreach ($list as $item){
            $find = Db::name('department_sj')->where('id',$item['d_id'])->find();
            if(!empty($find)){
                $data['amount6'] = $item['amount6'];
                Db::name('department_sj')->where('id',$item['d_id'])->update($data);
            }
        }
        return zy_json_echo(true, "保存成功", '', 200);
    }


    /**
     * 领导优秀处打分
     */
    public function addDepartmentGradeByAdmin(){
        $res = $this->request->param();
        $uid = '';
        $month = date('m',time());
        $year = date('Y',time());
        $list = $res['tableData'];
        foreach ($list as $item){
            $find = Db::name('department_sj')->where('id',$item['d_id'])->find();
            if(!empty($find)){
                $data['amount3'] = $item['amount3'];
                $data['status'] = 1;
                Db::name('department_sj')->where('id',$item['d_id'])->update($data);
            }
            $uid = $find['uid'];
        }
        if(!empty($uid)){
            $all_total_grade = $res['all_total_grade'];
            $find = Db::name('rank_history')->where('type',1)->where('month',$month)->where('year',$year)->where('uid',$uid)->find();
            if(!empty($find)){
                $department_id = $find['department_id'];
                if($all_total_grade != $find['leader_grade']){
                    if(!empty($find['leader_grade'])){
                        //先减后加
                        Db::name('department_month')->where('department_id',$department_id)->where('month',$month)->where('year',$year)->setDec('score',$find['leader_grade']);
                        Db::name('department_year')->where('department_id',$department_id)->where('year',$year)->setDec('score',$find['leader_grade']);
                    }
                    $this->changeMonthAndYear($department_id,$month,$year,$all_total_grade);
                }
                $up_data['leader_grade'] = $all_total_grade;
                $up_data['leader_grade_time'] = time();
                Db::name('rank_history')->where('id',$find['id'])->update($up_data);
            }
        }
        return zy_json_echo(true, "保存成功", '', 200);
    }

    public function changeMonthAndYear($department_id,$month,$year,$score){
        //添加月度总分
        $dep_month = Db::name('department_month')->where('department_id',$department_id)->where('month',$month)->where('year',$year)->find();
        if(empty($dep_month)){
            //添加
            $data['department_id'] = $department_id;
            $data['score'] = $score;
            $data['month'] = $month;
            $data['year'] = $year;
            Db::name('department_month')->insert($data);
        }else{
            //更新
            Db::name('department_month')->where('id',$dep_month['id'])->setInc('score',$score);
        }

        //添加年度总分
        $dep_year = Db::name('department_year')->where('department_id',$department_id)->where('year',$year)->find();
        if(empty($dep_year)){
            //添加
            $y_data['department_id'] = $department_id;
            $y_data['score'] = $score;
            $y_data['year'] = $year;
            Db::name('department_year')->insert($y_data);
        }else{
            //更新
            Db::name('department_year')->where('id',$dep_year['id'])->setInc('score',$score);
        }
    }

    /**
     * 排行榜
     */
    public function rankList(){
        $month = date('m',time());
        $year = date('Y',time());
        $res = $this->request->param();
        $type = $res['type'];//1.本月 2.年度
        if($type == 1){
            $sumScore = Db::name('department_month')->where('month',$month)->where('year',$year)->sum('score');
            $list = Db::name('department_month')->where('month',$month)->where('year',$year)->order('score','desc')->select()->each(function ($item,$index) use ($sumScore) {
                $item['index'] = $index+1;
                $userDetail = Db::name('department')->where('id', $item['department_id'])->find();
                $item['department_name'] = $userDetail['name'];
                $item['percentage'] = round(($item['score']/$sumScore)*100,2);
                return $item;
            });
        }else{
            $sumScore = Db::name('department_year')->where('year',$year)->sum('score');
            $list = Db::name('department_year')->where('year',$year)->order('score','desc')->select()->each(function ($item,$index) use ($sumScore) {
                $item['index'] = $index+1;
                $userDetail = Db::name('department')->where('id', $item['department_id'])->find();
                $item['department_name'] = $userDetail['name'];
                $item['percentage'] = round(($item['score']/$sumScore)*100,2);
                return $item;
            });
        }
        return zy_json_echo(true, "查询成功", $list, 200);
    }



    /**
     * 领导县市区打分
     */
    public function addAreaGradeByAdmin(){
        $res = $this->request->param();
        //上个月代码
        $timestamp = time();
        $firstDay = date('Y-m-01', strtotime(date('Y', $timestamp) . '-' . (date('m', $timestamp) - 1) . '-01'));
        $lastMonth = date('m', strtotime("$firstDay +1 month -1 day"));

        $uid = '';
        $month = date('m',time());
        $year = date('Y',time());
        $list = $res['tableData'];
        foreach ($list as $item){
            $find = Db::name('department_sj')->where('id',$item['d_id'])->find();
            $uid = $find['uid'];
            if(!empty($find)){
                //获取上个月的总分
//                $data =[];
//                $lastMonthGrade = Db::name('department_sj')->where('month',$lastMonth)->where('year',$year)->where('type',$find['type'])->where('uid',$uid)->where('mark',$find['mark'])->find();
//                if(empty($lastMonthGrade)){
//                    $data['amount5'] = $item['amount3'];
//                }elseif(empty($item['amount5'])){
//                    $data['amount5'] = $item['amount3'];
//                }else{
//                    $data['amount5'] =  ($data['amount5']-$find['amount3'])+$item['amount3'];
//                }
                $data['amount3'] = $item['amount3'];
                if($item['amount3']>$item['amount4']){
                    $data['amount3'] = $item['amount4'];
                }
                $data['status'] = 1;
                Db::name('department_sj')->where('id',$item['d_id'])->update($data);
            }

        }
        if(!empty($uid)){
            $all_total_grade = $res['all_total_grade'];
            $find = Db::name('rank_history')->where('type',2)->where('month',$month)->where('year',$year)->where('uid',$uid)->find();
            if(!empty($find)){
                $up_data['leader_grade'] = $all_total_grade;
                $up_data['leader_grade_time'] = time();
                Db::name('rank_history')->where('id',$find['id'])->update($up_data);
            }
        }
        return zy_json_echo(true, "保存成功", '', 200);
    }
    /**
     * 判断有无填写
     */
    public function checkReport(){
        $res = $this->request->param();
        $departmentId = $res['departmentId'];
        //获取已添加的详情
        $month = date('m',time());
        $year = date('Y',time());
        $counts = Db::name('department_sj')->where('department_id',$departmentId)->where('month',$month)->where('year',$year)->where('type',2)->count();
        if($counts == 0){
            return zy_json_echo(false, "该地区未填写评分", '该地区未填写评分', 300);
        }
        return zy_json_echo(true, "获取成功", '', 200);
    }

    /**
     * 获取优秀处列表和各个优秀处的人员列表
     */
    public function getOfficeList(){

        $res = $this->request->param();

        $where = 'id not in (1,13,14,15,16,17,18,19,20,21)';
        $department_list = Db::name('department')->where($where)->select();
        $office_id = $department_list[0]['id'];
        if(!empty($res['office_id'])){
            $office_id = $res['office_id'];
        }

        $userId = '0';
        if(!empty($office_id)){
            $attachList = Db::name('user_attach')->where('department_id',$office_id)->select();
            foreach ($attachList as $item){
                if(!empty($userId)){
                    $userId .= ',';
                }
                $userId .= $item['user_id'];
            }
        }

        $user_where = 'id in ('.$userId.')';
        $user_list = Db::name('user')->where($user_where)->select();

        $res = [
            'department_list'=>$department_list,
            'office_id'=>$office_id,
            'user_list'=>$user_list,
        ];
        return zy_json_echo(true, "获取成功", $res, 200);
    }

    /**
     * 获取省各地区月总分和年度总分
     */
    public function sumAreaGrade(){
        $month = date('m',time());
        $year = date('Y',time());
//        //循环部门列表
        $where = 'id in (13,14,15,16,17,18,19,20,21)';
        $department_list = Db::name('department')->where($where)->select()->each(function ($item) use ($year, $month) {
            //获取月总分
            $all_grade = Db::name('rank_history')->where('type',2)->where('month',$month)->where('year',$year)->where('department_id',$item['id'])->sum('leader_grade');

            $year_all_grade = Db::name('rank_history')->where('type',2)->where('year',$year)->where('department_id',$item['id'])->sum('leader_grade');

            $item['all_grade'] = $all_grade;
            $item['year_all_grade'] = $year_all_grade;
            return $item;
        });
        return zy_json_echo(true, "获取成功", $department_list, 200);
    }




    /**
     * 部门审计 -------------- 结束
     */

    public function personal_audit(){
        return $this->fetch();
    }
    public function personal_admin_audit(){
        return $this->fetch();
    }
    public function uploadWeb(){
        return $this->fetch();
    }

    /**
     *管路员添加提交
     */
    public function addPost()
    {
        if (!$this->request->isPost()) {
            $this->error('请求类型错误！');
        }
        $res = $this->request->param();
        $data = $res['post'];
        if (empty($data['user_login'])) {
            $this->error('用户名不能为空！');
        }
        if (empty($data['user_pass']) || empty($data['d_pass'])) {
            $this->error('密码不能为空！');
        }
        if (strlen($data['user_pass']) < 6 || strlen($data['user_pass']) > 16) {
            $this->error('密码长度不合法，长度应为6-16位！');
        }
        if (strlen($data['d_pass']) < 6 || strlen($data['d_pass']) > 16) {
            $this->error('确认密码长度不合法，长度应为6-16位！');
        }
        if ($data['user_pass'] !== $data['d_pass']) {
            $this->error('两次输入的密码不一致！');
        }
        $roleId = $res['role_id'];
        if (false === $this->checkRoleAccess($roleId)) {
            $this->error('当前用户无权限添加所选角色,请检查!');
        }
        unset($data['d_pass']);
        //生成密码
        $data['user_pass'] = cmf_password($data['user_pass']);
        // 启动事务
        Db::startTrans();
        try {
            $userId = Db::name('user')->insertGetId($data);
            $attach['department_id'] = Db::name('role')->where('id', $res['role_id'])->value('department_id');
            $attach['role_id'] = $res['role_id'];
            $attach['company_id'] = $res['company_id'];
            $attach['user_id'] = $userId;
            Db::name('user_attach')->insert($attach);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error('添加失败，请稍后再试！');
        }
        $this->autoCreateRank();
        $this->success('添加成功！');
    }

    /**
     * 人才管理导入
     */
    public function exportInTable(){
        $uid = cmf_get_current_admin_id();
        $userDetail = Db::name('user')->where('id', $uid)->find();
        $param = $this->request->param();
        //2.加载PHPExcle类库
        vendor('PHPExcel.PHPExcel');
        //设置获取excel对象
        $objReader = \PHPExcel_IOFactory::createReader('Excel2007');//配置成2003版本，因为office版本可以向下兼容
        $objPHPExcel = $objReader->load('upload/'.$param['path'],$encode='utf-8');//$file 为解读的excel文件
        $sheet = $objPHPExcel->getSheet(0);
        $highestRow = $sheet->getHighestRow(); // 取得总行数

        //开始读取数据
        for($j=2;$j<=$highestRow;$j++){
            $form['name'] = $objPHPExcel->getActiveSheet()->getCell('A'.$j)->getValue();//姓名
            $form['sex'] = $objPHPExcel->getActiveSheet()->getCell('B'.$j)->getValue();//性别
            $form['birthday'] = $objPHPExcel->getActiveSheet()->getCell('C'.$j)->getValue();//出生日期
            $form['nation'] = $objPHPExcel->getActiveSheet()->getCell('D'.$j)->getValue();//民族
            $form['native_place'] = $objPHPExcel->getActiveSheet()->getCell('E'.$j)->getValue();//籍贯
            $form['join_time'] = $objPHPExcel->getActiveSheet()->getCell('F'.$j)->getValue();//入党时间
            $form['work_time'] = $objPHPExcel->getActiveSheet()->getCell('G'.$j)->getValue();//参加工作时间
            $form['health'] = $objPHPExcel->getActiveSheet()->getCell('H'.$j)->getValue();//健康状态
            $form['avatar'] = $objPHPExcel->getActiveSheet()->getCell('I'.$j)->getValue();//证件照
            $form['born_address'] = $objPHPExcel->getActiveSheet()->getCell('J'.$j)->getValue();//出生地
            $form['technology'] = $objPHPExcel->getActiveSheet()->getCell('K'.$j)->getValue();//专业技术职位
            $form['specialty'] = $objPHPExcel->getActiveSheet()->getCell('L'.$j)->getValue();//特长
            $full_time_schooling_one = $objPHPExcel->getActiveSheet()->getCell('M'.$j)->getValue();//全日制教育一
            $full_time_schooling_two = $objPHPExcel->getActiveSheet()->getCell('N'.$j)->getValue();//全日制教育二
            $graduate_school_one_one = $objPHPExcel->getActiveSheet()->getCell('O'.$j)->getValue();//毕业院校1-1
            $graduate_school_one_two = $objPHPExcel->getActiveSheet()->getCell('P'.$j)->getValue();//毕业院校1-2
            $online_schooling_one = $objPHPExcel->getActiveSheet()->getCell('Q'.$j)->getValue();//在职教育一
            $online_schooling_two = $objPHPExcel->getActiveSheet()->getCell('R'.$j)->getValue();//在职教育二
            $graduate_school_two_one = $objPHPExcel->getActiveSheet()->getCell('S'.$j)->getValue();//毕业院校2-1
            $graduate_school_two_two = $objPHPExcel->getActiveSheet()->getCell('T'.$j)->getValue();//毕业院校2-2
            $form['work_unit'] = $objPHPExcel->getActiveSheet()->getCell('U'.$j)->getValue();//工作单位及职位
            $form['resume'] = $objPHPExcel->getActiveSheet()->getCell('V'.$j)->getValue();//简介
            $form['rewards'] = $objPHPExcel->getActiveSheet()->getCell('W'.$j)->getValue();//奖惩综述
            $form['assessment'] = $objPHPExcel->getActiveSheet()->getCell('X'.$j)->getValue();//年度考核综述
            $form['company_id'] = $objPHPExcel->getActiveSheet()->getCell('Y'.$j)->getValue();//统计关系所在单位id
            $form['company'] = $objPHPExcel->getActiveSheet()->getCell('Z'.$j)->getValue();//统计关系所在单位
            $form['id_card'] = $objPHPExcel->getActiveSheet()->getCell('AA'.$j)->getValue();//身份证号
            $form['manage_type'] = $objPHPExcel->getActiveSheet()->getCell('AB'.$j)->getValue();//管理类别
            $form['person_type'] = $objPHPExcel->getActiveSheet()->getCell('AC'.$j)->getValue();//人员类别
            $form['organization_type'] = $objPHPExcel->getActiveSheet()->getCell('AD'.$j)->getValue();//编制类别
            $form['job_type'] = $objPHPExcel->getActiveSheet()->getCell('AE'.$j)->getValue();//职位类别
            $form['leader_position'] = $objPHPExcel->getActiveSheet()->getCell('AF'.$j)->getValue();//现领导职位
            $form['leader_position_time'] = $objPHPExcel->getActiveSheet()->getCell('AG'.$j)->getValue();//任现领导时间
            $form['now_position'] = $objPHPExcel->getActiveSheet()->getCell('AH'.$j)->getValue();//现职级
            $form['now_position_time'] = $objPHPExcel->getActiveSheet()->getCell('AI'.$j)->getValue();//任现职级时间
            $form['position_level'] = $objPHPExcel->getActiveSheet()->getCell('AJ'.$j)->getValue();//任相当层次
            $form['job_rank_time'] = $objPHPExcel->getActiveSheet()->getCell('AK'.$j)->getValue();//职务职级时间
            $family_one = $objPHPExcel->getActiveSheet()->getCell('AL'.$j)->getValue();//家庭成员1
            $family_two = $objPHPExcel->getActiveSheet()->getCell('AM'.$j)->getValue();//家庭成员2
            $family_three = $objPHPExcel->getActiveSheet()->getCell('AN'.$j)->getValue();//家庭成员3
            $family_four = $objPHPExcel->getActiveSheet()->getCell('AO'.$j)->getValue();//家庭成员4
            $family_five = $objPHPExcel->getActiveSheet()->getCell('AP'.$j)->getValue();//家庭成员5
            $family_six = $objPHPExcel->getActiveSheet()->getCell('AQ'.$j)->getValue();//家庭成员6

            $family_all = $family_one.';'.$family_two.';'.$family_three.';'.$family_four.';'.$family_five.';'.$family_six;
            $family_arr = explode(";",$family_all);

            if(!empty($full_time_schooling_one) || !empty($full_time_schooling_two)){
                $form['full_time_schooling'] = $full_time_schooling_one.','.$full_time_schooling_two;
            }
            if(!empty($graduate_school_one_one) || !empty($graduate_school_one_two)){
                $form['graduate_school_one'] = $graduate_school_one_one.','.$graduate_school_one_two;
            }
            if(!empty($online_schooling_one) || !empty($online_schooling_two)){
                $form['online_schooling'] = $online_schooling_one.','.$online_schooling_two;
            }
            if(!empty($graduate_school_two_one) || !empty($graduate_school_two_two)){
                $form['graduate_school_two'] = $graduate_school_two_one.','.$graduate_school_two_two;
            }

            $form['add_time'] = time();
            $form['update_time'] = time();
            $form['update_person'] = $userDetail['user_login'];
            $talentId = Db::name('talent_management')->insertGetId($form);
            if(!empty($talentId)){
                foreach ($family_arr as $item){
                    $data['talent_id'] = $talentId;
                    $data['appellation'] = '';
                    $data['name'] = '';
                    $data['birthday'] = '';
                    $data['political_outlook'] = '';
                    $data['job'] = '';
                    if(!empty($item)){
                        $item_arr = explode(",",$item);
                        if(!empty($item_arr[0])){
                            $data['appellation'] = $item_arr[0];
                        }
                        if(!empty($item_arr[1])){
                            $data['name'] = $item_arr[1];
                        }
                        if(!empty($item_arr[2])){
                            $data['birthday'] = $item_arr[2];
                        }
                        if(!empty($item_arr[3])){
                            $data['political_outlook'] = $item_arr[3];
                        }
                        if(!empty($item_arr[4])){
                            $data['job'] = $item_arr[4];
                        }
                    }
                    Db::name('family')->insert($data);
                }
            }
        }
        return zy_json_echo(true, "添加成功", '', 200);
    }

    /**
     *人才管理添加提交
     */
    public function addTalentManage()
    {
        $uid = cmf_get_current_admin_id();
        $userDetail = Db::name('user')->where('id', $uid)->find();
        if (!$this->request->isPost()) {
            $this->error('请求类型错误！');
        }
        $res = $this->request->param();
        $family_data = htmlspecialchars_decode($res['family']);
        $family = json_decode($family_data,true);//家庭主要成员及社会重要关系

        $form_data = htmlspecialchars_decode($res['form_data']);
        $form = json_decode($form_data,true);
        $form['add_time'] = time();
        $form['update_time'] = time();
        $form['update_person'] = $userDetail['user_login'];
        $talentId = Db::name('talent_management')->insertGetId($form);

        foreach ($family as $item){
            $item['talent_id'] = $talentId;
            Db::name('family')->insert($item);
        }
        if($talentId){
            return zy_json_echo(true, "添加成功", '', 200);
        }
        return zy_json_echo(false, "添加失败", '', 300);
    }

    /**
    *人才管理修改提交
    */
    public function editTalentManage()
    {
        $uid = cmf_get_current_admin_id();
        $userDetail = Db::name('user')->where('id', $uid)->find();
        if (!$this->request->isPost()) {
            $this->error('请求类型错误！');
        }
        $res = $this->request->param();
        $family_data = htmlspecialchars_decode($res['family']);
        $family = json_decode($family_data,true);//家庭主要成员及社会重要关系

        $form_data = htmlspecialchars_decode($res['form_data']);
        $form = json_decode($form_data,true);
        $form['update_time'] = time();
        $form['update_person'] = $userDetail['user_login'];
        $result = Db::name('talent_management')->where('id',$res['id'])->update($form);
        Db::name('family')->where('talent_id',$res['id'])->delete();
        foreach ($family as $item){
            $item['talent_id'] = $res['id'];
            Db::name('family')->insert($item);
        }
        if($result){
            return zy_json_echo(true, "修改成功", '', 200);
        }
        return zy_json_echo(false, "修改失败", '', 300);
    }

    /**
     *人才管理删除
     */
    public function deletedTalentManage()
    {
        $res = $this->request->param();
        $result = Db::name('talent_management')->where('id',$res['id'])->delete();
        if($result){
            Db::name('family')->where('talent_id',$res['id'])->delete();
        }
        if($result){
            return zy_json_echo(true, "删除成功", '', 200);
        }
        return zy_json_echo(false, "删除失败", '', 300);
    }

    /**
     *19家单位人才管理列表
     */
    public function companyManageList()
    {
        $param = $this->request->param();
        $where = '1=1';
        if(!empty($param['id'])){
            $where .= ' and id='.$param['id'];
        }
        $list = Db::name('cooperation')->where($where)->paginate(20);
        return zy_json_echo(true, "获取成功", $list, 200);
    }

    /**
     *人才管理列表
     */
    public function talentManageList()
    {
        $res = $this->request->param();
        $where = '1=1';
        if(!empty($res['company'])){
            $where.=" and company='".$res['company']."'";
        }
        if(!empty($res['company_id'])){
            $where.=" and company_id='".$res['company_id']."'";
        }
        if(!empty($res['name'])){
            $where .= " and name like '%".$res['name']."%'";
        }
        if(!empty($res['id_card'])){
            $where .= " and id_card like '%".$res['id_card']."%'";
        }
        if(!empty($res['work_unit'])){
            $where .= " and work_unit like '%".$res['work_unit']."%'";
        }
        $list = Db::name('talent_management')->where($where)->paginate(20);
        return zy_json_echo(true, "获取成功", $list, 200);
    }
    /**
     *人才管理详情
     */
    public function talentManageDetail()
    {
        $param = $this->request->param();
        $detail = Db::name('talent_management')->where('id',$param['id'])->find();
        $avatar_url = '';
        if(!empty($detail['avatar'])){
            $avatar_url = ZY_APP_PATH.'upload/'.$detail['avatar'];
        }
        //家庭成员
        $list = Db::name('family')->where('talent_id',$param['id'])->select();
        $res = [
            'detail'=>$detail,
            'list'=>$list,
            'avatar_url'=>$avatar_url,
        ];
        return zy_json_echo(true, "获取成功", $res, 200);
    }

    /**

     * 判断权限

     */

    private function checkRoleAccess($roleId)
    {

        $uid = cmf_get_current_admin_id();

        $currentRoleId = Db::name('user_attach')->where('user_id', $uid)->value('role_id');

        $currentRole = Db::name('role')->where('id', $currentRoleId)->find();

        if ($currentRole['parent_id'] == 0) {

            return true;

        }

        //获取当前角色下的所有角色ids

        $fn = function ($roleId) use (&$fn) {

            $list = [];

            $roles = Db::name('role')->where('parent_id', $roleId)->column('id');

            foreach ($roles as $key => $value) {

                $list[] = $value;

                $list = array_merge($list, $fn($value));

            }

            return $list;

        };

        $accessRoles = $fn($currentRoleId);

        if (in_array($roleId, $accessRoles)) {

            return true;

        }

        return false;

    }

    /**

     * 管理员添加提交

     * @adminMenu(

     *     'name'   => '管理员添加提交',

     *     'parent' => 'index',

     *     'display'=> false,

     *     'hasView'=> false,

     *     'order'  => 10000,

     *     'icon'   => '',

     *     'remark' => '管理员添加提交',

     *     'param'  => ''

     * )

     */

    public function erwei($id)
    {

        Vendor('phpqrcode.phpqrcode');

        $url = 'http://oa.300c.cn/api/login/user?id=' . $id;

        $url = urldecode($url);

        $object = new \QRcode();

        ob_clean(); //这个一定要加上，清除缓冲区

        $object->png($url, false, 'Q', '6', '2');

    }

    public function xiangxi()
    {

        $id = $this->request->param('id', 0, 'intval');

        $user = DB::name('user')->where(["id" => $id])->find();

        $this->assign($user);

        $info = json_decode($user['fujian'], true);

        $this->roleList();

        $this->assign('info', $info);

        $date = DB::name('role_user')->where(["user_id" => $id])->find();

        $gw = DB::name('role')->where(["id" => $date['role_id']])->find();

        $sjgw = DB::name('role')->where(["id" => $gw['parent_id']])->find();

        $this->assign('sjgw', $sjgw);

        $this->assign('gw', $gw);

        return $this->fetch();

    }

    public function bak()
    {

        $id = $this->request->param('id', 0, 'intval');

        $date = DB::name('user_attach')->where(["user_id" => $id])->find();

        $userid = DB::name('role')->where(["id" => $date['role_id']])->find();

        $gw = DB::name('role')->where(["department_id" => $userid['department_id']])->select();

        $this->assign('gw', $gw);

        return $this->fetch();

    }

    /**

     * 管理员编辑

     * @adminMenu(

     *     'name'   => '管理员编辑',

     *     'parent' => 'index',

     *     'display'=> false,

     *     'hasView'=> true,

     *     'order'  => 10000,

     *     'icon'   => '',

     *     'remark' => '管理员编辑',

     *     'param'  => ''

     * )

     */

    public function edit()
    {

        $data = $this->request->param();

        $id = $this->request->param('id', 0, 'intval');

        $user = DB::name('user')->where(["id" => $id])->find();

        $role = Db::table('cmf_role')

            ->where('id', '=', function ($query) use ($id) {

                $query->table('cmf_user_attach')->where('user_id', $id)->field('role_id');

            })->find();

        $this->assign('role', json_encode($role));

        $this->assign($user);

        //读取所在公司角色列表 并分层级

        $accessModel = new AccessModel();

        $company = $accessModel->get_company_info();

        //获取当前用户所在公司角色列表信息

        $roles = $accessModel->get_company_role_list();

        $result = $roles;

        $tree = new Tree();

        //角色

        $tree->icon = ['│ ', '├─ ', '└─ '];

        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';

        foreach ($result as $m) {

            $newMenus[$m['id']] = $m;

        }

        foreach ($result as $n => $t) {

            $result[$n]['level'] = $this->_getLevel($t['id'], $newMenus);

            $result[$n]['style'] = empty($t['parent_id']) ? '' : 'display:none;';

            $result[$n]['parentIdNode'] = ($t['parent_id']) ? ' class="child-of-node-' . $t['parent_id'] . '"' : '';

        }

        $str2 = "<option value = \$id data-dep=\$department_id>\$spacer\$name</option>";

        $tree->init($result);

        $role = $tree->getTree(0, $str2);

        $this->assign('company', $company);

        $this->assign('roleList', $role);

        $this->assign("userid", $id);

        return $this->fetch();

    }

    /**

     * 管理员资料编辑提交

     */

    public function editPost()
    {

        if (!$this->request->isPost()) {
            $this->error('请求类型错误！');
        }
        $res = $this->request->param();
        $userId = $res['id'];
        $data = $res['post'];
        if (empty($data['user_login'])) {
            $this->error('用户名不能为空！');
        }
        if (cmf_get_current_admin_id() != 1 && $userId == 1) {
            $this->error('超级管理员账号信息禁止修改！');
        }
        if ($userId == 1 && $res['role_id'] != 1) {
            $this->error("超级管理员角色禁止修改！");
        }
        $roleId = $res['role_id'];
        if (false === $this->checkRoleAccess($roleId)) {
            $this->error('当前用户无权限添加所选角色,请检查!');
        }
        //检查用户名是否重复
        $user = Db::name('user')->where('user_login', $data['user_login'])->find();
        if (!empty($user) && $user['id'] != $userId) {
            $this->error('用户名已经存在，请重新输入！');
        }
        if (!empty($res['user_pass'])) {
            if (empty($res['user_pass']) || empty($res['d_pass'])) {
                $this->error('密码不能为空！');
            }
            if (strlen($res['user_pass']) < 6 || strlen($res['user_pass']) > 16) {
                $this->error('密码长度不合法，长度应为6-16位！');
            }
            if (strlen($res['d_pass']) < 6 || strlen($res['d_pass']) > 16) {
                $this->error('确认密码长度不合法，长度应为6-16位！');
            }
            if ($res['user_pass'] !== $res['d_pass']) {
                $this->error('两次输入的密码不一致！');
            }
            $data['user_pass'] = cmf_password($res['d_pass']);
        }
        // 启动事务
        Db::startTrans();
        try {
            if ($userId == 1) {
                $authorM = new \app\admin\model\AuthorizationModel();
                $mdyPwd['password'] = $res['d_pass'];
                $result = $authorM->modifyPwd($mdyPwd);
                if (!(!empty($result) && isset($result['status']) && $result['status'] == 'success')) {
                    $this->error("修改失败，请稍后再试！");
                }
            }
            $updateRes = Db::name('user')->where('id', $userId)->update($data);
            $attach['department_id'] = Db::name('role')->where('id', $res['role_id'])->value('department_id');
            $attach['role_id'] = $res['role_id'];
            Db::name('user_attach')->where('user_id', $userId)->update($attach);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error('信息更新失败，请稍后再试！');
        }
        $this->success('信息更新成功！');
    }

    /**

     * 管理员个人信息修改

     * @adminMenu(

     *     'name'   => '个人信息',

     *     'parent' => 'index',

     *     'display'=> false,

     *     'hasView'=> true,

     *     'order'  => 10000,

     *     'icon'   => '',

     *     'remark' => '管理员个人信息修改',

     *     'param'  => ''

     * )



    public function userInfo()

    {



    $id    = cmf_get_current_admin_id();

    $user = DB::name('user')->where(["id" => $id])->find();

    $this->assign($user);

    $this->roleList();



    $roles = Db::name('role')->where(['status' => 1])->order("id DESC")->select();





    $info1 = Db::name('user_attach')->where(['user_id' => $id])->find();





    $ids = cmf_get_current_admin_id();



    $qx = Db::name('user_attach')->where(['user_id' => $ids])->find();

    $name = Db::name('role')->where(['id' => $info1["role_id"]])->find();



    $this->assign("info1", $info1);



    $this->assign("roles", $roles);

    $this->assign("qx", $qx);

    $this->assign("name", $name);

    $this->assign("userid", $id);



    $info = json_decode($user['fujian'], true);



    $this->assign('info', $info);



    return $this->fetch();

    }



    /**

     * 管理员个人信息修改提交

     * @adminMenu(

     *     'name'   => '管理员个人信息修改提交',

     *     'parent' => 'index',

     *     'display'=> false,

     *     'hasView'=> false,

     *     'order'  => 10000,

     *     'icon'   => '',

     *     'remark' => '管理员个人信息修改提交',

     *     'param'  => ''

     * )

     */

    public function userInfoPost()
    {

        if ($this->request->isPost()) {

            $data = $this->request->post();

            $data['birthday'] = strtotime($data['birthday']);

            $data['id'] = cmf_get_current_admin_id();

            $create_result = Db::name('user')->update($data);

            if ($create_result !== false) {

                $this->success("保存成功！");

            } else {

                $this->error("保存失败！");

            }

        }

    }

    /**

     * 管理员删除

     * @adminMenu(

     *     'name'   => '管理员删除',

     *     'parent' => 'index',

     *     'display'=> false,

     *     'hasView'=> false,

     *     'order'  => 10000,

     *     'icon'   => '',

     *     'remark' => '管理员删除',

     *     'param'  => ''

     * )

     */

    public function delete()
    {

        $id = $this->request->param('id', 0, 'intval');

        if ($id == 1) {

            $this->error("最高管理员不能删除！");

        }

        if (Db::name('user')->delete($id) !== false) {

            Db::name('user_attach')->where('user_id', $id)->delete();

            $this->success("删除成功！");

        } else {

            $this->error("删除失败！");

        }

    }

    /**

     * 停用管理员

     * @adminMenu(

     *     'name'   => '停用管理员',

     *     'parent' => 'index',

     *     'display'=> false,

     *     'hasView'=> false,

     *     'order'  => 10000,

     *     'icon'   => '',

     *     'remark' => '停用管理员',

     *     'param'  => ''

     * )

     */

    public function ban()
    {

        $id = $this->request->param('id', 0, 'intval');

        if (!empty($id)) {

            $result = Db::name('user')->where(["id" => $id, "user_type" => 1])->setField('user_status', '0');

            if ($result !== false) {

                $this->success("管理员停用成功！", url("user/index"));

            } else {

                $this->error('管理员停用失败！');

            }

        } else {

            $this->error('数据传入失败！');

        }

    }

    /**

     * 启用管理员

     * @adminMenu(

     *     'name'   => '启用管理员',

     *     'parent' => 'index',

     *     'display'=> false,

     *     'hasView'=> false,

     *     'order'  => 10000,

     *     'icon'   => '',

     *     'remark' => '启用管理员',

     *     'param'  => ''

     * )

     */

    public function cancelBan()
    {

        $id = $this->request->param('id', 0, 'intval');

        if (!empty($id)) {

            $result = Db::name('user')->where(["id" => $id, "user_type" => 1])->setField('user_status', '1');

            if ($result !== false) {

                $this->success("管理员启用成功！", url("user/index"));

            } else {

                $this->error('管理员启用失败！');

            }

        } else {

            $this->error('数据传入失败！');

        }

    }

    public function userInfoEdit()
    {

        $id = cmf_get_current_admin_id();

        $data = $this->request->param();

        if ($data) {

            $data['id'] = $id;

            unset($data['d_pass']);

            $res = Db::name('user')->update($data);

            if ($res !== false) {

                $this->success('更改成功');

            } else {

                $this->error('更改失败');

            }

        }

        if (!$data) {

            $data = Db::name('user')->find($id);

            $this->assign('data', $data);

            $this->roleList();

            return $this->fetch();

        }

    }

    public function qingjia()
    {

        $userid = $this->request->param('id', 0, 'intval');

        $username = Db::name('user')->where('id', $userid)->find();

        $this->assign('userid', $userid);

        $this->assign('username', $username);

        return $this->fetch();

    }

    public function ck_qj()
    {

        $Qj = new AttendanceModel();

        $userid = $this->request->param('id', 0, 'intval');

        $this->request->isPost(); //接收post

        $start = $this->request->param("start"); //接收post所有數據

        $end = $this->request->param("end"); //接收post所有數據

        if ($start != 0 && $end != 0) {

            $start = strtotime($start);

            $end = strtotime($end);

            $info = $Qj::where('start_time', '>', $start)->where('end_time', '<', $end)->where('userid', $userid)->select();

        } else {

            $info = $Qj::where('userid', $userid)->select();

        }

        $this->view->assign('info', $info);

        $this->assign('userid', $userid);

        return $this->fetch();

    }

    public function qj_add()
    {

        $Qj = new AttendanceModel();

        $data = $this->request->param();

        $data['post']['start_time'] = strtotime($data['post']['start_time']);

        $data['post']['end_time'] = $data['post']['start_time'] + $data['post']['time'] * 86400;

        $userid = Db::name('user_attach')->where('user_id', $data['post']['userid'])->find();

        if ($userid['role_id'] == 62) {

            $time = Db::name('user')->where('id', $data['post']['userid'])->find();

            $rz_time = [

                'rz_time' => $time['rz_time'] + $data['post']['time'] * 86400,

            ];

            Db::name('user')->where('id', $data['post']['userid'])->update($rz_time);

        }

        $result = $Qj::insert($data['post']);

        if ($result) {

            $this->success('添加成功', url("user/index"));

        } else {

            $this->error('添加失败');

        }

    }

    public function qj_del()
    {

        $id = $this->request->param('id', 0, 'intval');

        $uid = Db::name('attendance')->where('id', $id)->find();

        $userid = Db::name('user_attach')->where('user_id', $uid['userid'])->find();

        if ($userid['role_id'] == 62) {

            $time = Db::name('user')->where('id', $uid['userid'])->find();

            $rz_time = [

                'rz_time' => $time['rz_time'] - $uid['time'] * 86400,

            ];

            Db::name('user')->where('id', $uid['userid'])->update($rz_time);

        }

        $del = Db::name('attendance')->where(['id' => $id])->delete();

        if ($del) {

            $this->success("删除成功！");

        } else {

            $this->error("删除失败！");

        }

    }

    public function qj_edit()
    {

        $id = $this->request->param('id', 0, 'intval');

        $Qj = new AttendanceModel();

        $info = Db::name('attendance')->where(['id' => $id])->find();

        $this->view->assign('info', $info);

        if ($this->request->isPost()) {

            $data = $this->request->param();

            $data['post']['start_time'] = strtotime($data['post']['start_time']);

            $data['post']['end_time'] = $data['post']['start_time'] + $data['post']['time'] * 86400;

            $uid = Db::name('attendance')->where('id', $data['id'])->find();

            $userid = Db::name('user_attach')->where('user_id', $uid['userid'])->find();

            if ($userid['role_id'] == 62) {

                $time = Db::name('user')->where('id', $uid['userid'])->find();

                $rz_time = [

                    'rz_time' => $time['rz_time'] - $uid['time'] * 86400 + $data['post']['time'] * 86400,

                ];

                Db::name('user')->where('id', $uid['userid'])->update($rz_time);

            }

            $edit = $Qj::where('id', $data['id'])->update($data['post']);

            if ($edit) {

                $this->success("修改成功！", url("user/ck_qj"));

            } else {

                $this->error("修改失败！");

            }

        }

        return $this->fetch();

    }

    /**

     * 个人电子名片页面

     */

    public function businesscard()
    {

        $result = Db::name('business_card')->where('userid=' . cmf_get_current_admin_id())->order(['sort' => 'desc', 'modify_time' => 'desc'])->select();

        foreach ($result as $key => $value) {

            $value['content'] = cmf_replace_content_file_url(htmlspecialchars_decode($value['content']));

            $result[$key] = $value;

        }

        $signature = Db::name('user')->where('id=' . cmf_get_current_admin_id())->find()['signature'];

        $this->assign('userid', cmf_get_current_admin_id());

        $this->assign('signature', cmf_replace_content_file_url(htmlspecialchars_decode($signature)));

        $this->assign('list', $result);

        return $this->fetch();

    }

    /**

     * 修改个性签名

     */

    public function setSignature()
    {

        $con = $this->request->param()['content'];

        Db::name('user')->where('id=' . cmf_get_current_admin_id())->update(['signature' => $con]);

    }

    /**

     * 个人名片页面提交

     * @return [type] [description]

     */

    public function businesscard_post()
    {

        if ($this->request->isPost()) {

            //dump($this->request);

            if (!isset($this->request->post()['post'])) {

                $this->error('请填写展示内容，再提交！');

            }

            $data = $this->request->post()['post'];

            $in['content'] = $data['bak'];

            if (strlen(trim($in['content'])) == 0) {

                $this->error('请填写展示内容，再提交！');

            }

            $in['add_time'] = time();

            $in['modify_time'] = time();

            $in['userid'] = cmf_get_current_admin_id();

            Db::name('business_card')->insert($in);

            $this->success('添加成功！');

        } else {

            $this->error('请求错误！');

        }

    }

    /**

     * 个人名片操作

     * @return [type] [description]

     */

    public function operate()
    {

        if ($this->request->isPost()) {

            $data = $this->request->post();

            if (-1 == $data['type']) {
//删除

                Db::name('business_card')->where('id=' . $data['id'] . " and userid=" . $data['userid'])->delete();

            } else {

                $up = ['sort' => $data['type']];

                //置顶取消置顶

                if ($data['type'] == 1) {

                    $up['modify_time'] = time();

                }

                Db::name('business_card')->where('id=' . $data['id'] . " and userid=" . $data['userid'])->update($up);

            }

            return json(['code' => 1, 'msg' => '']);

        } else {

            return json(['code' => 0, 'msg' => '请求类型错误！']);

        }

    }

    /**

     * 用户签名页面

     * @return [type] [description]

     */

    public function sign()
    {

        $id = cmf_get_current_admin_id();

        $user = Db::name('user')->where('id=' . $id)->find();

        $this->assign('user', $user);

        return $this->fetch();

    }

    /**

     * 用户签名二维码

     * @return [type] [description]

     */

    public function yhqm_erweima($id)
    {

        $request = Request::instance();

        $domain = $request->domain();

        Vendor('phpqrcode.phpqrcode');

        $url = $domain . '/portal/index/yhqm?id=' . $id;

        $url = urldecode($url);

        $object = new \QRcode();

        ob_clean(); //这个一定要加上，清除缓冲区

        $object->png($url, false, 'Q', '6', '2');

    }

    /**

     * 删除签名

     * @return [type] [description]

     */

    public function delesign()
    {

        $data = $this->request->post();

        Db::name('user')->where("id=" . $data['id'])->update(['sign' => ""]);

        return 1;

    }

    /**

     * 获取token

     * @return [type] [description]

     */

    public function getToken()
    {

        if ($this->request->isPost()) {

            $data = $this->request->post();

            $user = Db::name('user')->where('id=' . $data['id'])->find();

            $res = get_rongyun_token($user['id'], $user['user_login']);

            if ($res['code'] == 200) {

                //将获取的token放入数据库

                Db::name('user')->where('id=' . $data['id'])->update(['ry_token' => $res['token']]);

                return 1;

            } else {

                return $res['code'];

            }

        }

    }

    /**

     * 更新员工编号

     * @return [type] [description]

     */

    public function update_employee_id()
    {

        $user = Db::name('user')->where('user_type=1 and user_status=1')->select();

        foreach ($user as $arr) {

            $NO = getEmployeeId($arr['id']);

            Db::name('user')->where('id=' . $arr['id'])->update(['employee_id' => $NO]);

        }

        return $this->success('更新成功！');

    }

}
